import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/team/soccer/zq_team_detail_logic.dart';
import 'package:sports_new/entity/team/zq_team_detail_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';

import '../../../resources/get_icon.dart';
import '../../../widgets/base/qkd_text.dart';

class ZqTeamInfoView extends StatefulWidget {
  const ZqTeamInfoView({super.key});

  @override
  State<ZqTeamInfoView> createState() => _ZqTeamInfoViewState();
}

class _ZqTeamInfoViewState extends State<ZqTeamInfoView> {
  // final controller = Get.put(SoccerTeamInfoController());
  int teamId = Get.arguments;
  ZqTeamDetailLogic detailC =
      Get.find<ZqTeamDetailLogic>(tag: '${Get.arguments}');
  List<bool> dataList = List.generate(20, (index) => false).toList();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colours.scaffoldBg,
      padding: const EdgeInsets.fromLTRB(8, 0, 8, 10),
      child: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        removeBottom: true,
        child: GetBuilder<ZqTeamDetailLogic>(
          tag: teamId.toString(),
          builder: (_) {
            return detailC.data == null
                ? Container()
                : ((teamDataEmpty() &&
                        detailC.data?.honorView == null &&
                        detailC.data!.introduce.hasValue != true)
                    ? const NoDataWidget()
                    : ListView(
                        children: [
                          if (!teamDataEmpty()) teamData().marginOnly(top: 8),
                          if (detailC.data?.honorView != null)
                            teamHonor().marginOnly(top: 8),
                          if (detailC.data!.introduce.hasValue)
                            teamInfo().marginOnly(top: 8),
                          const SizedBox(height: 50),
                        ],
                      ));
          },
        ),
      ),
    );
  }

  bool teamDataEmpty() {
    return detailC.data?.foundingDate.hasValue != true &&
        detailC.data?.countryCn.hasValue != true &&
        detailC.data?.areaCn.hasValue != true &&
        detailC.data?.gymCn.hasValue != true &&
        detailC.data?.addrCn.hasValue != true &&
        detailC.data?.website.hasValue != true;
  }

  Widget teamData() {
    return Container(
      padding: const EdgeInsets.fromLTRB(12, 16, 12, 8),
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: Colours.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          QkdText(
            '基本资料',
            fontSize: 16, fontWeight: FontWeight.w500
          ),
          if (detailC.data?.foundingDate.hasValue == true)
            infoItem('成立时间', detailC.data!.foundingDate ?? ''),
          if (detailC.data?.countryCn.hasValue == true ||
              detailC.data?.areaCn.hasValue == true)
            infoItem(
                '所在地区',
                '${detailC.data?.countryCn.hasValue == true
                    ? '${detailC.data?.countryCn} '
                    : ''}${detailC.data?.areaCn}'),
          if (detailC.data?.gymCn.hasValue == true)
            infoItem(
                '球队主场',
                '${detailC.data?.gymCn}${detailC.data?.capacity.hasValue == true
                        ? '·可容纳${detailC.data?.capacity}人'
                        : ''}'),
          if (detailC.data?.addrCn.hasValue == true)
            infoItem('球队地址', detailC.data?.addrCn ?? ''),
          if (detailC.data?.website.hasValue == true)
            infoItem('球队网址', detailC.data?.website ?? ''),
          const SizedBox(height: 8)
        ],
      ),
    );
  }

  Widget infoItem(String title, String content) {
    return Row(
      children: [
        QkdText(title, color: Colours.grey66),
        const SizedBox(width: 12),
        Expanded(
          child: QkdText(
            content,
            color: Colours.text,
            maxLines: 2,
          ),
        ),
      ],
    ).marginOnly(top: 8);
  }

  Widget teamHonor() {
    return Container(
      padding: const EdgeInsets.fromLTRB(12, 16, 4, 8),
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: Colours.white,
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        QkdText(
          '球队荣誉',
          fontSize: 16, fontWeight: FontWeight.w500
        ),
        const SizedBox(height: 8),
        ...detailC.data!.honorView!.map((e) {
          return Column(
            children: [
              ExpandablePanel(
                header: Row(
                  children: [
                    Image.asset(
                      Utils.getImgPath('champion_cup.png'),
                      width: 16,
                    ),
                    const SizedBox(
                      width: 4,
                      height: 40,
                    ),
                    QkdText(
                      e.leagueName ?? '',
                      fontWeight: FontWeight.w500
                    ),
                    QkdText(
                      '（${e.size.toString()}次）',
                      color: Colours.grey99
                    ),
                  ],
                ),
                theme: ExpandableThemeData(
                    iconSize: 12,
                    iconPadding:
                        const EdgeInsets.symmetric(vertical: 14, horizontal: 8),
                    // useInkWell: false,
                    // crossFadePoint: 0.2,
                    collapseIcon: GetIcon.menu_arrow_up,
                    expandIcon: GetIcon.menu_arrow_down,
                    hasIcon: e.size! > 3,
                    tapHeaderToExpand: e.size! > 3),
                collapsed: honorList(e, false),
                expanded: honorList(e, true),
              ),
              const SizedBox(height: 8)
            ],
          );
        }),
      ]),
    );
  }

  honorList(HonorView data, bool expanded) {
    final width = (Get.width - 32 - 16 - 60 - 20) / 3;
    return Wrap(
        spacing: 10,
        runSpacing: 10,
        children: List.generate(
            expanded ? data.size! : (data.size! > 3 ? 3 : data.size!),
            (index) => Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(2),
                  color: Colours.greyF5F7FA,
                ),
                height: 24,
                width: width,
                child: QkdText(
                  data.season![index],
                  color: Colours.grey66, fontSize: 12
                ))));
  }

  Widget teamInfo() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: Colours.white,
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        QkdText(
          '球队简介',
          fontSize: 16, fontWeight: FontWeight.w500
        ),
        const SizedBox(height: 8),
        Html(
            data: getInfoStr(),
            style: {
              "body": Style(letterSpacing: -0.5),
            }),
      ]),
    );
  }

  String getInfoStr() {
    var regCom = RegExp(r'<\/p>[.\n]<p>');
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    String append = '';
    String? com = detailC.data?.introduce
        ?.split("<p>&nbsp;</p>")
        .join("<div style= 'height: 20;width: 200px;'>  </div>")
        .split(regCom)
        .join("</p><div style= 'height: 20;width: 200px;'>  </div><p>")
        .split("/><p>")
        .join("/><div style= 'height: 20;width: 200px;'>  </div><p>")
        .split("/><img")
        .join("/><div style= 'height: 20;width: 200px;'>  </div><img");
    com?.split("").forEach((element) {
      if (regC.hasMatch(element)) {
        append += "$element\u200A";
      } else {
        append += element;
      }
    });
    var newData = "";
    newData = """
    <!DOCTYPE html>
      <html>
        <body style="margin: 0 0 0 0"><div style="color: #FF444444;margin: 0;font-size: 14px; line-height: 1.3; letter-spacing: -1px; white-space: normal; text-align: justify;">$append</div></body>
      </html>
      <style>
      p{
        margin: 0;
      }
      </style>
    """;
    return newData;
  }
}
